<template>
  <div class="mainos">
    <div class="main_spac1 paddingBottom5">
      <div class="main_white padding10 paddingBottom20">
        <div class="main_crumbs boxdq">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>结算</span>
          </div>
          <div class="main_crumbs_rt"></div>
        </div>
        <div class="main_tile boxdq marginTop10">
          <div class="main_tile_l marginLeft0"><em></em>基础信息</div>
        </div>
        <el-form
          :inline="false"
          :rules="rules"
          :model="info"
          class="demo-form-inline"
          ref="userListFrom1"
          label-width="0"
          key="userListFrom1"
        >
          <div class="main_xq">
            <ul class="boxha">
              <li>
                采购方式：<span>{{
                  info.data.modeList[info.data.info.mode]
                }}</span>
              </li>
              <li>
                采购员/供应商：<span>{{
                  info.data.info.buyerAndSupplier
                }}</span>
              </li>
              <li>
                应付金额：<span>{{ info.data.info.money }}</span>
              </li>
              <li>
                已付金额：<span>{{ info.data.info.paid }}</span>
              </li>
              <li>
                未付金额：<span>{{ info.data.info.unpaid }}</span>
              </li>
              <li>
                本次付款总金额：
                <el-input
                  placeholder="本次付款金额"
                  v-model="totals.total"
                  @blur="totalSet"
                >
                </el-input>
                <!-- <span>{{ total.pay_money }}</span> -->
              </li>
              <li>
                账期：<span>{{ info.data.info.payment_days.toString() }}</span>
              </li>
              <li>
                <div class="Settlement">
                  全部结算：
                  <el-switch
                    class="mainor_switch"
                    active-text="开"
                    inactive-text="关"
                    v-model="SettlementAll"
                    active-color="#03A98E"
                    inactive-color="#DCDFE6"
                  >
                  </el-switch>
                  <el-popover
                    placement="top-start"
                    title="提示"
                    width="200"
                    trigger="hover"
                    content="开启时会全额结算，所有订单根据输入内容自动平账。关闭后可部分结算,当应付金额为负数时总抹零功能会被禁用"
                  >
                    <el-button
                      type="text"
                      slot="reference"
                      icon="el-icon-info"
                    ></el-button>
                  </el-popover>
                </div>
              </li>
              <li>
                本次抹零总金额：
                <el-input
                  placeholder="本次抹零金额"
                  v-model.lazy="totals.zero_total"
                  @blur="zero_moneySet"
                   :disabled='SettlementAll==false&& info.data.info.unpaid<0'
                >
                </el-input>
              </li>
              <div class="clearfix"></div>

              <li class="main_w100 marginTop10 boxha boxnr">
                付款方式：
                <span class="main_xqs" style="width: 30%">
                  <el-form-item
                    label=""
                    prop="info_form.pay_type"
                    :rules="rules.pay_type"
                  >
                    <el-select
                      v-model.trim="info.info_form.pay_type"
                      placeholder="付款方式"
                      class="wid220"
                      @change="isEdit = true"
                    >
                      <el-option
                        v-for="(pay_type_list, index) in info.data
                          .pay_type_list"
                        :key="index"
                        :label="pay_type_list"
                        :value="parseInt(index)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </span>
              </li>

              <li class="main_w100 marginTop15 boxha boxnr">
                收款人：
                <span class="main_xqs" style="width: 30%">
                  <el-form-item
                    label=""
                    prop="info_form.payee"
                    :rules="rules.payee"
                  >
                    <el-input
                      v-model.trim="info.info_form.payee"
                      placeholder="收款人"
                      clearable
                      @change="isEdit = true"
                    ></el-input>
                  </el-form-item>
                </span>
              </li>
              <li class="main_w100 marginTop15 boxha boxnr">
                备注：
                <span class="main_xqs" style="margin-left: 12px">
                  <el-form-item label="" prop="info_form.remark">
                    <el-input
                      v-model.trim="info.info_form.remark"
                      placeholder="备注"
                      clearable
                      @change="isEdit = true"
                    ></el-input>
                  </el-form-item>
                </span>
              </li>
              <li class="main_w100 marginTop15 boxha">
                上传凭证(3张)：
                <span class="main_xqs">
                  <div class="box main_xqi">
                    <div class="main_upImg">
                      <el-upload
                        :action="uploadPath"
                        list-type="picture-card"
                        :on-success="handSuccess"
                        :on-remove="handleRemove"
                        :limit="3"
                        :headers="{
                          Authorization: getToken()
                        }"
                        :file-list="filelist"
                      >
                        <span slot="default">
                          <svg
                            aria-hidden="true"
                            class="main_page_svg"
                            width="32"
                            height="27"
                          >
                            <use xlink:href="#icon-commodit_camera" />
                          </svg>
                        </span>
                      </el-upload>
                      <div class="clearfix"></div>
                    </div>
                  </div>
                </span>
              </li>
            </ul>
          </div>
          <div class="main_tile boxdq marginTop10">
            <div class="main_tile_l marginLeft0"><em></em>订单详情</div>
          </div>
          <div class="main_table marginTop0"></div>
          <div class="main_table marginTop0">
            <el-table
              ref="multipleTable1"
              v-loading="listLoading"
              :data="info.data.list"
              element-loading-text="加载中"
              fit
              highlight-current-row
              key="multipleTable1"
            >
              <el-table-column
                label="单据号"
                prop="order_sn"
                class-name="main_hei"
                min-width="140"
                show-overflow-tooltip
              />
              <el-table-column
                label="单据类型"
                min-width="120"
                show-overflow-tooltip
              >
                <template slot-scope="scope">{{
                  info.data.typeList[scope.row.type]
                }}</template>
              </el-table-column>
              <el-table-column
                label="应付金额"
                prop="account_money"
                class-name="main_hei"
                min-width="120"
                show-overflow-tooltip
              />
              <el-table-column
                label="已付金额"
                prop="paid"
                class-name="main_hei"
                min-width="120"
                show-overflow-tooltip
              />
              <el-table-column
                label="抹零金额"
                prop="zero_amount_copy"
                class-name="main_hei"
                min-width="120"
                show-overflow-tooltip
              />

              <el-table-column
                label="未付金额"
                prop="unpaid"
                class-name="main_hei"
                min-width="120"
                show-overflow-tooltip
              />
              <el-table-column
                label="本次付款金额"
                prop="unpaid"
                class-name="main_hei"
                min-width="120"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'data.list.' + scope.$index + '.pay_money'"
                    :rules="rules.pay_money"
                    label-width="10px"
                    label=" "
                  >
                    <el-input
                      v-model.trim="scope.row.pay_money"
                      placeholder="付款金额"
                      class="wid110"
                      @change="isEdit = true"
                      @blur="setzero_money(scope)"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="本次抹零金额"
                prop="zero_amount"
                class-name="main_hei"
                min-width="120"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'data.list.' + scope.$index + '.zero_amount'"
                    :rules="rules.zero_amount"
                    label-width="10px"
                    label=" "
                  >
                    <el-input
                      v-model.trim="scope.row.zero_amount"
                      placeholder="抹零金额"
                      class="wid110"
                      @change="isEdit = true"
                      @blur="setpay_money(scope)"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="剩余未付"
                class-name="main_hei"
                min-width="120"
                show-overflow-tooltip
              >
                <template slot-scope="scope">{{
                  scope.row.unpaid - scope.row.pay_money
                    ? $toFixed(
                        scope.row.unpaid -
                          scope.row.pay_money -
                          scope.row.zero_amount
                      )
                    : "0.00"
                }}</template>
              </el-table-column>
              <el-table-column
                label="备注"
                prop="remark"
                width="350"
                class-name="main_hei"
                min-width="120"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-form-item label-width="0" label="">
                    <el-input
                      v-model.trim="scope.row.remark"
                      placeholder="备注"
                      class="wid240"
                      @change="isEdit = true"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <span class="footer_red">合计:￥{{ total.zs }}</span>
          <el-button type="primary" @click="settupmine" v-repeatClick
            >结 算</el-button
          >
        </div>
      </div>
    </div>
    <!-- 打印子组件 -->
  </div>
</template>

<script>
import {
  account_index,
  account_paid,
  account_getList
} from "@/api/financial/financialRecharge";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/financial/financialRecharge";
import { parseTime } from "@/utils/index";
import { uploadPath } from "@/api/currency";
export default {
  computed: {
    total() {
      let zs = 0;
      let pay_money = 0;
      this.info.data.list.forEach(e => {
        zs += parseFloat(this.$toFixed(parseFloat(e.pay_money)));
        pay_money += parseFloat(this.$toFixed(parseFloat(e.pay_money)));
      });
      zs = this.$toFixed(zs);
      pay_money = this.$toFixed(pay_money);
      return {
        zs,
        pay_money
      };
    },
    zero_total() {
      let zs = 0;
      let collected_now = 0;
      this.info.data.list.forEach(e => {
        zs += parseFloat(this.$toFixed(parseFloat(e.zero_amount)));
      });
      return zs ? this.$toFixed(zs) : 0;
    }
  },
  watch: {
    "info.data.list": {
      handler(newVal, oldVal) {
        this.totals.zero_total = this.zero_total;
        this.totals.total = this.total.pay_money;
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      // 时间
      parseTime,
      // 验证
      rules,
      uploadPath,
      // 上传图片
      filelist: [],
      //结算方式开关
      SettlementAll: true,
      // 基本信息
      info: {
        info: {
          money: 0,
          created_at: "2000-01-01",
          type: 0,
          status: 0,
          mode: 0,
          account_statement_list: []
        },
        buyer: ["未分拣"],
        modeList: ["未分拣"],
        supplier: ["未分拣"],
        typeList: ["未分拣"],
        account_status_list: ["未分拣"],
        statusList: ["未分拣"]
      },
      info_form: {
        mode: null,
        buyer_id: null,
        supplier_id: null,
        pay_type: null,
        payee: "",
        remark: "",
        pics: []
      },
      listLoading: false,

      //  结算
      info: {
        data: {
          info: {
            order_sn: "",
            contact: "",
            mobile: "",
            address: "",
            payment_days: "",
            admin_user_name: {
              name: ""
            }
          },
          list: [],
          buyer: {},
          modeList: ["未分拣"],
          supplier: ["未分拣"],
          pay_type_list: ["未分拣"],
          typeList: ["未分拣"],
          direct_supply: {}
        },
        info_form: {
          mode: null,
          buyer_id: null,
          supplier_id: null,
          pay_type: null,
          payee: "",
          remark: "",
          pics: []
        }
      },
      ids: this.$route.params,
      type: "",
      isEdit: false,
      totals: { zero_total: "", total: "" }
    };
  },
  created() {
    // 基本信息
    this.get_info(2);
  },

  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            // 正常跳转
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  methods: {
    // 基本信息
    get_info() {
      if (!this.$route.params.ids) {
        return;
      }
      let str = this.$route.params.ids;
      let ids_arr = str.split(",");
      let arr = [];
      ids_arr.map(e => {
        arr.push({
          id: e
        });
      });

      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        { ids: JSON.stringify(arr) }
      );
      account_getList(data).then(res => {
        if (res.errcode == 0) {
          res.data.list.map(e => {
            e.pay_money = e.unpaid;
            e.zero_amount_copy = e.zero_amount;
            e.zero_amount = 0;
          });
          this.info.info_form.mode = res.data.info.mode;
          this.info.info_form.supplier_id = res.data.info.supplier_id;
          this.info.info_form.buyer_id = res.data.info.buyer_id;
          this.info.data = res.data;
          this.info.data.info.buyerAndSupplier = this.buyerAndSupplierTable();
          this.settFormVisible = true;
        } else {
          this.$message.error(res.errmsg);
          this.$router.back(-1);
        }
      });
    },
    buyerAndSupplierTable() {
      let flag = null;
      let info = this.info.data;
      try {
        switch (info.info.mode) {
          case 1:
            flag = info.buyer[info.info.buyer_id];
            break;
          case 2:
            flag = info.supplier[info.info.supplier_id];
            break;
          case 3:
            flag = info.direct_supply[info.info.supplier_id];
            break;
        }
      } catch (error) {
        console.log(error);
      }
      return flag;
    },
    // 上传图片-删除
    handleRemove(file) {
      this.isEdit = true;
      const i = this.info.info_form.pics.findIndex(
        item => item.path == file.path
      );
      this.info.info_form.pics.splice(i, 1);
    },
    // 上传图片-成功
    handSuccess(res, file, fileList) {
      // console.log(res, file, fileList);
      this.isEdit = true;
      this.info.info_form.pics.push({
        name: "",
        path: res.data.path,
        url: res.data.src
      });
    },
    // 结算
    settupmine() {
      this.$refs["userListFrom1"].validate(valid => {
        if (valid) {
          this.$confirm("确定结算吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              let arry = [];
              let info = JSON.parse(JSON.stringify(this.info));
              info.info_form.pics = info.info_form.pics
                .map(e => e.path)
                .join(",");

              //   info.data.list.map(e => {
              //     arry.push({
              //       id: e.id,
              //       pay_money: e.pay_money,
              //       zero_amount: e.zero_amount,
              //       remark: e.remark
              //     });
              //   });
              let dataInfo = {};
              info.data.list.forEach((item, index) => {
                let { payment_days } = item;
                if (!dataInfo[payment_days]) {
                  dataInfo[payment_days] = {
                    payment_days,
                    child: []
                  };
                }
                dataInfo[payment_days].child.push({
                  id: item.id,
                  pay_money: item.pay_money,
                  zero_amount: item.zero_amount,
                  remark: item.remark
                });
              });
              let list = Object.values(dataInfo);
              list.forEach(e => {
                arry.push(e.child);
              });
              let data = Object.assign(
                {
                  sign: Md5(
                    objKeySort(Object.assign(apiUrl().name)) +
                      apiUrl().appsecret
                  )
                },
                apiUrl().name,
                info.info_form,
                { list: JSON.stringify(arry) }
              );
              account_paid(data).then(res => {
                this.settFormVisible = false;
                if (res.errcode == 0) {
                  this.$message({
                    message: "结算成功",
                    type: "success"
                  });
                  this.isEdit = false;
                  this.$router.back(-1);
                } else {
                  this.$message.error(res.errmsg);
                }
              });
            })
            .catch(() => {});
        }
      });
    },
    //自动生成收款
    setpay_money(scope) {
      if (this.SettlementAll) {
        scope.row.zero_amount = this.$toFixed(scope.row.zero_amount);
        scope.row.pay_money = this.$toFixed(
          scope.row.unpaid - scope.row.zero_amount
        );
      }
    },
     //自动生成抹零金额
    setzero_money(scope) {
       if (this.SettlementAll) {
      scope.row.pay_money = this.$toFixed(scope.row.pay_money);
      scope.row.zero_amount = this.$toFixed(
        scope.row.unpaid - scope.row.pay_money
      );}
    },
    //设置零钱
    zero_moneySet(set) {
      let num = +this.totals.zero_total;
      if (num == 0) {
        this.info.data.list.forEach(e => {
          e.zero_amount = 0;
        });
      }
      if (this.SettlementAll) {
        this.totals.total = this.$toFixed(
          this.info.data.info.unpaid - num
        );
        this.totalSet(set);
      }
      this.info.data.list.sort((a, b) => {
        return b.unpaid - a.unpaid;
      });
      this.info.data.list.forEach(e => {
        if (e.unpaid - e.pay_money === 0) {
          e.zero_amount = 0;
        } else if (e.unpaid - e.pay_money - num >= 0&&(num>=0||this.SettlementAll==false)) {
          e.zero_amount = this.$toFixed(num);
          num = 0;
        } else {
          num = this.$toFixed(num - (e.unpaid - e.pay_money));
          // console.log(num,this.$toFixed(e.unpaid - e.pay_money));
          e.zero_amount = this.$toFixed(e.unpaid - e.pay_money);
        }
      });
    },
    //设置总收款
    totalSet(set) {
      let num = +this.totals.total;
      //解决存在负数时num自动减小
      if (num >= 0) {
        this.info.data.list.forEach(e => {
          if (e.unpaid < 0) {
            num -= e.unpaid;
          }
        });
      }
       if (this.SettlementAll&&set!=1) {
        this.totals.zero_total = this.$toFixed(
          this.info.data.info.unpaid - this.$toFixed(this.totals.total) 
        );
          this.zero_moneySet(1)
      }
      this.info.data.list.sort((a, b) => {
        return b.unpaid - a.unpaid;
      });
      if (num < 0) {
        if (num < this.total.pay_money) {
          this.totals.total = this.total.pay_money;
        }
        this.info.data.list.forEach(e => {
          if (e.unpaid - num <= 0) {
            e.pay_money = this.$toFixed(num);
            num = 0;
          } else {
            num = this.$toFixed(num - e.unpaid);
            e.pay_money = this.$toFixed(e.unpaid);
          }
        });
        return;
      }

      this.info.data.list.forEach(e => {
        if (e.unpaid - num >= 0) {
          e.pay_money = num;
          num = 0;
        } else {
          //不將负数带入运算
          // if (e.unpaid < 0||this.totals.total==) {
          //   e.pay_money = 0;
          // } else {}
          num = this.$toFixed(num - e.unpaid);
          e.pay_money = e.unpaid;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

/deep/.el-upload-list--picture-card .el-upload-list__item {
  padding-left: 0 !important;
}
.mainos {
  .main_tile {
    .mainos_tile_r {
      color: $colour_red;
      font-size: $font_14;
    }
  }
  .mainor_ex {
    position: fixed;
    width: 220px;
    height: 100%;
    background: $white;
    box-shadow: 0 6px 10px rgba(0, 21, 41, 0.08);
    top: 0;
    right: 0;
    z-index: 9999;
    transition: all 0.5s;
    transform: translate3d(100%, 0, 0);
    &.on {
      transform: translate3d(0, 0, 0);
    }
    .mainor_exb {
      position: absolute;
      width: 100%;
      height: calc(100% - 60px);
      overflow-y: auto;
      h3 {
        font-size: $font_16;
        color: $colour_18;
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid $colour_e6;
        padding-left: 20px;
      }
      .mainor_exb_an {
        padding-left: 20px;
        margin-top: 15px;
        /deep/.el-checkbox {
          display: block;
          margin-top: 15px;
          margin-bottom: 15px;
        }
      }
    }
    .mainor_exb_b {
      position: absolute;
      bottom: 0;
      width: 100%;
      border-top: 1px solid $colour_e6;
      height: 55px;
      text-align: center;
      /deep/.el-button--default {
        margin-top: 12px;
        border-color: $subActive;
        color: $menuText;
        &:hover {
          border-color: $menuActiveText;
          color: $menuActiveText;
        }
      }
    }
  }
}
.main_xq ul li {
  width: 33.33%;
  margin-top: 5px;
  margin-bottom: 5px;
  .main_xqs {
    width: 85%;
    display: block;
    text-align: left;
    /deep/.el-input--small {
      width: 100%;
    }
  }
}
.main_xq {
  /deep/.el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
}
.dialog-footer {
  text-align: right;
  margin-top: 15px;
  padding-right: 15px;
  .footer_red {
    font-size: 16px;
    color: red;
    margin-right: 10px;
  }
}
/deep/.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 0;
}
.disflex {
  margin-left: 280px;
  /deep/ .el-input__inner {
    width: 180px;
  }
}
.Settlement {
  font-size: 15px;
  color: #555;
  /deep/ .el-button {
    border: none;
    /deep/ .el-button:hover {
      border: none;
    }
  }
  /deep/.el-button--text {
    color: #555;
  }
}
.boxha li {
  display: flex;
  align-items: center;
}
</style>
